package unilearn.da;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.naming.*;
import javax.sql.DataSource;

public abstract class DABase {
	public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";

	public static final String PROTOCOL = "jdbc:derby:";

	private static Connection conn;

	private static Connection createConnection() throws SQLException,
			NamingException {
		Connection c;
		try {
			Class.forName(DRIVER).newInstance();
		} catch (ClassNotFoundException ex) {
			throw new Error(ex);
		} catch (Exception ex) {
			throw new Error(ex);
		}

		c = DriverManager.getConnection(PROTOCOL + "unilearndb;create=true");

		if (false) {
			// Obtain our environment naming context;
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");

			// Look up our data source
			DataSource ds = (DataSource) envCtx.lookup("jdbc/unilearndb");

			// Allocate and use a connection from the pool
			c = ds.getConnection();
		}

		return c;
	}

	public static Connection getConn() throws SQLException {
		try {
			if (conn == null) {
				conn = createConnection();
			} else if (conn.isClosed()) {
				conn = createConnection();
			}

			return conn;
		} catch (NamingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Shutdowns the Derby Database so it can be rebuild
	 * 
	 * Prevents Resource Locking
	 * 
	 */
	public static void shutdown() {
		try {
			if (conn != null)
				conn.close();

		} catch (SQLException e) {
			// Don't Care
		}
		conn = null;
		try {
			DriverManager.getConnection("jdbc:derby:unilearndb;shutdown=true");
		} catch (SQLException e) {
			// Don't Care
		}
	}
}
